﻿
using LitJson;
using System.IO;
using UnityEngine;

/// <summary>
/// JSON操作方案
/// </summary>
public enum JsonType
{
    JsonUtility,
    LitJson
}

/// <summary>
/// Json数据管理类,主要用于进行JSON的序列化和反序列化 读取与存储
/// </summary>
public class JsonMgr
{
    public static JsonMgr instance = new JsonMgr();
    public static JsonMgr Instance => instance;

    private JsonMgr() { }

    //存储
    public void Save(string fileName, object data, JsonType type = JsonType.LitJson)
    {
        //存储路径
        string path = string.Format("{0}/{1}.json", Application.persistentDataPath, fileName);
        //序列化的json字符串
        string jsonStr = "";
        switch (type)
        {
            case JsonType.JsonUtility:
                jsonStr = JsonUtility.ToJson(data);
                break;
            case JsonType.LitJson:
            default:
                jsonStr = JsonMapper.ToJson(data);
                break;
        }
        File.WriteAllText(path, jsonStr);
        Debug.LogFormat("[JsonMgr][Save] path:{0}", path);
    }

    public T Read<T>(string file, JsonType type=JsonType.LitJson) where T : new()
    {
        //先找默认路径下的数据
        string path = string.Format("{0}/{1}.json", Application.streamingAssetsPath, file);
        //不存在则在读写文件里查找
        if (!File.Exists(path))
            path = string.Format("{0}/{1}.json", Application.persistentDataPath, file);
        if (!File.Exists(path))
            return new T();
        Debug.LogFormat("[JsonMgr][Read] path:{0}", path);
        string jsonStr = File.ReadAllText(path);
        T data = default(T);
        switch (type)
        {
            case JsonType.JsonUtility:
                data = JsonUtility.FromJson<T>(jsonStr);
                break;
            case JsonType.LitJson:
            default:
                data = JsonMapper.ToObject<T>(jsonStr);
                break;
        }
        return data;
    }
}
